{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def TEForecast(ticker, dates, values ):    \n",
    "\n",
    "    url = 'https://api.tradingeconomics.com/historical/ticker/{tick}?client=guest:guest'.format(tick = ticker)\n",
    "    myDF = pd.read_json(url)\n",
    "    myDF['DateTime'] = pd.to_datetime(myDF['DateTime'])\n",
    "    myDF = myDF.set_index('DateTime')\n",
    "    startDate = datetime.datetime.today() - relativedelta(years = 5)\n",
    "    myDF = myDF[startDate:]\n",
    "    myDF = myDF[['HistoricalDataSymbol', 'Value']]\n",
    "    myDF = myDF.pivot_table(values='Value',\n",
    "                            index=myDF.index,\n",
    "                            columns='HistoricalDataSymbol',\n",
    "                            aggfunc='first')    \n",
    "    \n",
    "    data = np.array([values]).T\n",
    "    dates = [datetime.datetime.strptime(date, \"%Y-%m-%d\").date() for date in dates]\n",
    "    points = pd.DataFrame(data,\n",
    "                          index = dates,\n",
    "                          columns = [ticker])\n",
    "    \n",
    "    lastRowOriginal = myDF.tail(1)\n",
    "    forc = [lastRowOriginal, points]\n",
    "    forecasted = pd.concat(forc).sum(axis = 1)\n",
    "    forecasted.index = pd.to_datetime(forecasted.index)\n",
    "    forcBase = forecasted \n",
    "\n",
    "    forecasted = forecasted.reindex(pd.date_range(start=forecasted.index[0],\n",
    "                                                  end=forecasted.index[-1],\n",
    "                                                  freq='B'))  \n",
    "    forecasted = forecasted.interpolate(method='spline', order = 3)\n",
    "    noise = np.random.normal(scale = 0.05 * myDF.std(), size = len(forecasted))\n",
    "\n",
    "    forcNoise = forecasted + noise\n",
    "    forcNoise = forcNoise.to_frame()\n",
    "    forcNoise = forcNoise.drop(forcBase.index)\n",
    "    forcNoise = pd.concat([forcNoise, forcBase]).sort_index()\n",
    "    print forcNoise\n",
    "    results = {'historical':myDF, 'forecasted':forcNoise, 'points':points}\n",
    "    \n",
    "    return results"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
